package net.sf.rose.jdbc.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.Properties;

import org.apache.log4j.Logger;

import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;

/**
 * 功能：
 * @author fengjian
 * @since 2013/10/15
 */
public class SQLService {

	private static Logger logger = Logger.getLogger(SQLService.class);

	/** SQL配置文件名 */
	private static String SQL_FILE = "resource/sql.properties";

	/** 本地SQL语句文本信息类 */
	private static Properties sqlMetaBean = new Properties();

	static {
		// 加载SQL语句文件
		InputStream in = SQLService.class.getClassLoader().getResourceAsStream(SQL_FILE);
		if (in != null) {
			try {
				sqlMetaBean.load(in);
				in.close();
			} catch (IOException e) {
				String message = "初始化SQL语句库失败！";
				logger.error(message, e);
				throw new SystemException(message, SystemErrorCode.A_FILE_LOAD_ERROR);
			}
		}
	}
	
	/**
	 * 返回SQL语句
	 */
	public static String getSql(String sqlKey){
		String val = sqlMetaBean.getProperty(sqlKey);
		if (val == null) {
			String message = "SQL语句提取失败！";
			logger.error(message);
			throw new SystemException(message, SystemErrorCode.D_SQL_GET_ERROR);
		}
		return val;
	}

	/**
	 * 返回SQL语句
	 */
	public static String getSql(String sqlKey, Object... arguments) {
		try {
			return new MessageFormat(getSql(sqlKey)).format(arguments);
		} catch (MissingResourceException e) {
			String message = "SQL语句解析失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.D_SQL_RESOLVE_ERROR);
		}
	}
}
